/**
 * 图片上传
 * author rubekid
 */
(function(){
	/**
	 * 兼容console.log
	 */
	var console = window.console||{log:function(){}};
	window.jQuery = window.jQuery || window.Zepto;
	/* jpeg_encoder_basic.js  for android jpeg压缩质量修复 */
	function JPEGEncoder(a){function I(a){var c,i,j,k,l,m,n,o,p,b=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(c=0;64>c;c++)i=d((b[c]*a+50)/100),1>i?i=1:i>255&&(i=255),e[z[c]]=i;for(j=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],k=0;64>k;k++)l=d((j[k]*a+50)/100),1>l?l=1:l>255&&(l=255),f[z[k]]=l;for(m=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],n=0,o=0;8>o;o++)for(p=0;8>p;p++)g[n]=1/(8*e[z[n]]*m[o]*m[p]),h[n]=1/(8*f[z[n]]*m[o]*m[p]),n++}function J(a,b){var f,g,c=0,d=0,e=new Array;for(f=1;16>=f;f++){for(g=1;g<=a[f];g++)e[b[d]]=[],e[b[d]][0]=c,e[b[d]][1]=f,d++,c++;c*=2}return e}function K(){i=J(A,B),j=J(E,F),k=J(C,D),l=J(G,H)}function L(){var c,d,e,a=1,b=2;for(c=1;15>=c;c++){for(d=a;b>d;d++)n[32767+d]=c,m[32767+d]=[],m[32767+d][1]=c,m[32767+d][0]=d;for(e=-(b-1);-a>=e;e++)n[32767+e]=c,m[32767+e]=[],m[32767+e][1]=c,m[32767+e][0]=b-1+e;a<<=1,b<<=1}}function M(){for(var a=0;256>a;a++)x[a]=19595*a,x[a+256>>0]=38470*a,x[a+512>>0]=7471*a+32768,x[a+768>>0]=-11059*a,x[a+1024>>0]=-21709*a,x[a+1280>>0]=32768*a+8421375,x[a+1536>>0]=-27439*a,x[a+1792>>0]=-5329*a}function N(a){for(var b=a[0],c=a[1]-1;c>=0;)b&1<<c&&(r|=1<<s),c--,s--,0>s&&(255==r?(O(255),O(0)):O(r),s=7,r=0)}function O(a){q.push(w[a])}function P(a){O(255&a>>8),O(255&a)}function Q(a,b){var c,d,e,f,g,h,i,j,l,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,_,k=0;var _m=8,_n=64;for(l=0;_m>l;++l)c=a[k],d=a[k+1],e=a[k+2],f=a[k+3],g=a[k+4],h=a[k+5],i=a[k+6],j=a[k+7],p=c+j,q=c-j,r=d+i,s=d-i,t=e+h,u=e-h,v=f+g,w=f-g,x=p+v,y=p-v,z=r+t,A=r-t,a[k]=x+z,a[k+4]=x-z,B=.707106781*(A+y),a[k+2]=y+B,a[k+6]=y-B,x=w+u,z=u+s,A=s+q,C=.382683433*(x-A),D=.5411961*x+C,E=1.306562965*A+C,F=.707106781*z,G=q+F,H=q-F,a[k+5]=H+D,a[k+3]=H-D,a[k+1]=G+E,a[k+7]=G-E,k+=8;for(k=0,l=0;_m>l;++l)c=a[k],d=a[k+8],e=a[k+16],f=a[k+24],g=a[k+32],h=a[k+40],i=a[k+48],j=a[k+56],I=c+j,J=c-j,K=d+i,L=d-i,M=e+h,N=e-h,O=f+g,P=f-g,Q=I+O,R=I-O,S=K+M,T=K-M,a[k]=Q+S,a[k+32]=Q-S,U=.707106781*(T+R),a[k+16]=R+U,a[k+48]=R-U,Q=P+N,S=N+L,T=L+J,V=.382683433*(Q-T),W=.5411961*Q+V,X=1.306562965*T+V,Y=.707106781*S,Z=J+Y,$=J-Y,a[k+40]=$+W,a[k+24]=$-W,a[k+8]=Z+X,a[k+56]=Z-X,k++;for(l=0;_n>l;++l)_=a[l]*b[l],o[l]=_>0?0|_+.5:0|_-.5;return o}function R(){P(65504),P(16),O(74),O(70),O(73),O(70),O(0),O(1),O(1),O(0),P(1),P(1),O(0),O(0)}function S(a,b){P(65472),P(17),O(8),P(b),P(a),O(3),O(1),O(17),O(0),O(2),O(17),O(1),O(3),O(17),O(1)}function T(){var a,b;for(P(65499),P(132),O(0),a=0;64>a;a++)O(e[a]);for(O(1),b=0;64>b;b++)O(f[b])}function U(){var a,b,c,d,e,f,g,h;for(P(65476),P(418),O(0),a=0;16>a;a++)O(A[a+1]);for(b=0;11>=b;b++)O(B[b]);for(O(16),c=0;16>c;c++)O(C[c+1]);for(d=0;161>=d;d++)O(D[d]);for(O(1),e=0;16>e;e++)O(E[e+1]);for(f=0;11>=f;f++)O(F[f]);for(O(17),g=0;16>g;g++)O(G[g+1]);for(h=0;161>=h;h++)O(H[h])}function V(){P(65498),P(12),O(3),O(1),O(0),O(2),O(17),O(3),O(17),O(0),O(63),O(0)}function W(a,b,c,d,e){var h,l,o,q,r,s,t,u,v,w,f=e[0],g=e[240];var _i=16,_j=63,_k=64;for(l=Q(a,b),o=0;_k>o;++o)p[z[o]]=l[o];for(q=p[0]-c,c=p[0],0==q?N(d[0]):(h=32767+q,N(d[n[h]]),N(m[h])),r=63;r>0&&0==p[r];r--);if(0==r)return N(f),c;for(s=1;r>=s;){for(u=s;0==p[s]&&r>=s;++s);if(v=s-u,v>=_i){for(t=v>>4,w=1;t>=w;++w)N(g);v=15&v}h=32767+p[s],N(e[(v<<4)+n[h]]),N(m[h]),s++}return r!=_j&&N(f),c}function X(){var b,a=String.fromCharCode;for(b=0;256>b;b++)w[b]=a(b)}function Y(a){if(0>=a&&(a=1),a>100&&(a=100),y!=a){var b=0;b=50>a?Math.floor(5e3/a):Math.floor(200-2*a),I(b),y=a,console.log("Quality set to: "+a+"%")}}function Z(){var c,b=(new Date).getTime();a||(a=50),X(),K(),L(),M(),Y(a),c=(new Date).getTime()-b,console.log("Initialization "+c+"ms")}var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H;Math.round,d=Math.floor,e=new Array(64),f=new Array(64),g=new Array(64),h=new Array(64),m=new Array(65535),n=new Array(65535),o=new Array(64),p=new Array(64),q=[],r=0,s=7,t=new Array(64),u=new Array(64),v=new Array(64),w=new Array(256),x=new Array(2048),z=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],A=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],B=[0,1,2,3,4,5,6,7,8,9,10,11],C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],D=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],E=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],F=[0,1,2,3,4,5,6,7,8,9,10,11],G=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],H=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250],this.encode=function(a,b){var d,e,f,m,n,o,p,y,z,A,B,C,D,E,F,G,H,I,J,K,c=(new Date).getTime();for(b&&Y(b),q=new Array,r=0,s=7,P(65496),R(),T(),S(a.width,a.height),U(),V(),d=0,e=0,f=0,r=0,s=7,this.encode.displayName="_encode_",m=a.data,n=a.width,o=a.height,p=4*n,z=0;o>z;){for(y=0;p>y;){for(D=p*z+y,E=D,F=-1,G=0,H=0;64>H;H++)G=H>>3,F=4*(7&H),E=D+G*p+F,z+G>=o&&(E-=p*(z+1+G-o)),y+F>=p&&(E-=y+F-p+4),A=m[E++],B=m[E++],C=m[E++],t[H]=(x[A]+x[B+256>>0]+x[C+512>>0]>>16)-128,u[H]=(x[A+768>>0]+x[B+1024>>0]+x[C+1280>>0]>>16)-128,v[H]=(x[A+1280>>0]+x[B+1536>>0]+x[C+1792>>0]>>16)-128;d=W(t,g,d,i,k),e=W(u,h,e,j,l),f=W(v,h,f,j,l),y+=32}z+=8}return s>=0&&(I=[],I[1]=s+1,I[0]=(1<<s+1)-1,N(I)),P(65497),J="data:image/jpeg;base64,"+btoa(q.join("")),q=[],K=(new Date).getTime()-c,console.log("Encoding time: "+K+"ms"),J},Z()}function getImageDataFromImage(a){var d,b="string"==typeof a?document.getElementById(a):a,c=document.createElement("canvas");return c.width=b.width,c.height=b.height,d=c.getContext("2d"),d.drawImage(b,0,0),d.getImageData(0,0,c.width,c.height)}

	/* megapix-image.js for IOS(iphone5+) drawImage画面扭曲修复  */
	!function(){function a(a){var d,e,b=a.naturalWidth,c=a.naturalHeight;return b*c>1048576?(d=document.createElement("canvas"),d.width=d.height=1,e=d.getContext("2d"),e.drawImage(a,-b+1,0),0===e.getImageData(0,0,1,1).data[3]):!1}function b(a,b,c){var e,f,g,h,i,j,k,d=document.createElement("canvas");for(d.width=1,d.height=c,e=d.getContext("2d"),e.drawImage(a,0,0),f=e.getImageData(0,0,1,c).data,g=0,h=c,i=c;i>g;)j=f[4*(i-1)+3],0===j?h=i:g=i,i=h+g>>1;return k=i/c,0===k?1:k}function c(a,b,c){var e=document.createElement("canvas");return d(a,e,b,c),e.toDataURL("image/jpeg",b.quality||.8)}function d(c,d,f,g){var m,n,o,p,q,r,s,t,u,v,w,h=c.naturalWidth,i=c.naturalHeight,j=f.width,k=f.height,l=d.getContext("2d");for(l.save(),e(d,l,j,k,f.orientation),m=a(c),m&&(h/=2,i/=2),n=1024,o=document.createElement("canvas"),o.width=o.height=n,p=o.getContext("2d"),q=g?b(c,h,i):1,r=Math.ceil(n*j/h),s=Math.ceil(n*k/i/q),t=0,u=0;i>t;){for(v=0,w=0;h>v;)p.clearRect(0,0,n,n),p.drawImage(c,-v,-t),l.drawImage(o,0,0,n,n,w,u,r,s),v+=n,w+=r;t+=n,u+=s}l.restore(),o=p=null}function e(a,b,c,d,e){switch(e){case 5:case 6:case 7:case 8:a.width=d,a.height=c;break;default:a.width=c,a.height=d}switch(e){case 2:b.translate(c,0),b.scale(-1,1);break;case 3:b.translate(c,d),b.rotate(Math.PI);break;case 4:b.translate(0,d),b.scale(1,-1);break;case 5:b.rotate(.5*Math.PI),b.scale(1,-1);break;case 6:b.rotate(.5*Math.PI),b.translate(0,-d);break;case 7:b.rotate(.5*Math.PI),b.translate(c,-d),b.scale(-1,1);break;case 8:b.rotate(-.5*Math.PI),b.translate(-c,0)}}function f(a){var b,c,d;if(window.Blob&&a instanceof Blob){if(b=new Image,c=window.URL&&window.URL.createObjectURL?window.URL:window.webkitURL&&window.webkitURL.createObjectURL?window.webkitURL:null,!c)throw Error("No createObjectURL function found to create blob url");b.src=c.createObjectURL(a),this.blob=a,a=b}a.naturalWidth||a.naturalHeight||(d=this,a.onload=function(){var b,c,a=d.imageLoadListeners;if(a)for(d.imageLoadListeners=null,b=0,c=a.length;c>b;b++)a[b]()},this.imageLoadListeners=[]),this.srcImage=a}f.prototype.render=function(a,b){var e,f,g,h,i,j,k,l,m,n,o;if(this.imageLoadListeners)return e=this,this.imageLoadListeners.push(function(){e.render(a,b)}),void 0;b=b||{},f=this.srcImage.naturalWidth,g=this.srcImage.naturalHeight,h=b.width,i=b.height,j=b.maxWidth,k=b.maxHeight,l=!this.blob||"image/jpeg"===this.blob.type,h&&!i?i=g*h/f<<0:i&&!h?h=f*i/g<<0:(h=f,i=g),j&&h>j&&(h=j,i=g*h/f<<0),k&&i>k&&(i=k,h=f*i/g<<0),m={width:h,height:i};for(n in b)m[n]=b[n];o=a.tagName.toLowerCase(),"img"===o?a.src=c(this.srcImage,m,l):"canvas"===o&&d(this.srcImage,a,m,l),"function"==typeof this.onrender&&this.onrender(a)},"function"==typeof define&&define.amd?define([],function(){return f}):this.MegaPixImage=f}();

	/*
	 * Javascript EXIF Reader - jQuery plugin 0.1.3
	 * Copyright (c) 2008 Jacob Seidelin, cupboy@gmail.com, http://blog.nihilogic.dk/
	 * Licensed under the MPL License [http://www.nihilogic.dk/licenses/mpl-license.txt]
	 */
	(function(){var BinaryFile=function(strData,iDataOffset,iDataLength){var data=strData;var dataOffset=iDataOffset||0;var dataLength=0;this.getRawData=function(){return data};if(typeof strData=="string"){dataLength=iDataLength||data.length;this.getByteAt=function(iOffset){return data.charCodeAt(iOffset+dataOffset)&0xFF}}else if(typeof strData=="unknown"){dataLength=iDataLength||IEBinary_getLength(data);this.getByteAt=function(iOffset){return IEBinary_getByteAt(data,iOffset+dataOffset)}}this.getLength=function(){return dataLength};this.getSByteAt=function(iOffset){var iByte=this.getByteAt(iOffset);if(iByte>127)return iByte-256;else return iByte};this.getShortAt=function(iOffset,bBigEndian){var iShort=bBigEndian?(this.getByteAt(iOffset)<<8)+this.getByteAt(iOffset+1):(this.getByteAt(iOffset+1)<<8)+this.getByteAt(iOffset);if(iShort<0)iShort+=65536;return iShort};this.getSShortAt=function(iOffset,bBigEndian){var iUShort=this.getShortAt(iOffset,bBigEndian);if(iUShort>32767)return iUShort-65536;else return iUShort};this.getLongAt=function(iOffset,bBigEndian){var iByte1=this.getByteAt(iOffset),iByte2=this.getByteAt(iOffset+1),iByte3=this.getByteAt(iOffset+2),iByte4=this.getByteAt(iOffset+3);var iLong=bBigEndian?(((((iByte1<<8)+iByte2)<<8)+iByte3)<<8)+iByte4:(((((iByte4<<8)+iByte3)<<8)+iByte2)<<8)+iByte1;if(iLong<0)iLong+=4294967296;return iLong};this.getSLongAt=function(iOffset,bBigEndian){var iULong=this.getLongAt(iOffset,bBigEndian);if(iULong>2147483647)return iULong-4294967296;else return iULong};this.getStringAt=function(iOffset,iLength){var aStr=[];for(var i=iOffset,j=0;i<iOffset+iLength;i++,j++){aStr[j]=String.fromCharCode(this.getByteAt(i))}return aStr.join("")};this.getCharAt=function(iOffset){return String.fromCharCode(this.getByteAt(iOffset))};this.toBase64=function(){return window.btoa(data)};this.fromBase64=function(strBase64){data=window.atob(strBase64)}};var BinaryAjax=(function(){function createRequest(){var oHTTP=null;if(window.XMLHttpRequest){oHTTP=new XMLHttpRequest()}else if(window.ActiveXObject){oHTTP=new ActiveXObject("Microsoft.XMLHTTP")}return oHTTP}function getHead(strURL,fncCallback,fncError){var oHTTP=createRequest();if(oHTTP){if(fncCallback){if(typeof(oHTTP.onload)!="undefined"){oHTTP.onload=function(){if(oHTTP.status=="200"){fncCallback(this)}else{if(fncError)fncError()}oHTTP=null}}else{oHTTP.onreadystatechange=function(){if(oHTTP.readyState==4){if(oHTTP.status=="200"){fncCallback(this)}else{if(fncError)fncError()}oHTTP=null}}}}oHTTP.open("HEAD",strURL,true);oHTTP.send(null)}else{if(fncError)fncError()}}function sendRequest(strURL,fncCallback,fncError,aRange,bAcceptRanges,iFileSize){var oHTTP=createRequest();if(oHTTP){var iDataOffset=0;if(aRange&&!bAcceptRanges){iDataOffset=aRange[0]}var iDataLen=0;if(aRange){iDataLen=aRange[1]-aRange[0]+1}if(fncCallback){if(typeof(oHTTP.onload)!="undefined"){oHTTP.onload=function(){if(oHTTP.status=="200"||oHTTP.status=="206"||oHTTP.status=="0"){this.binaryResponse=new BinaryFile(this.responseText,iDataOffset,iDataLen);this.fileSize=iFileSize||this.getResponseHeader("Content-Length");fncCallback(this)}else{if(fncError)fncError()}oHTTP=null}}else{oHTTP.onreadystatechange=function(){if(oHTTP.readyState==4){if(oHTTP.status=="200"||oHTTP.status=="206"||oHTTP.status=="0"){this.binaryResponse=new BinaryFile(oHTTP.responseBody,iDataOffset,iDataLen);this.fileSize=iFileSize||this.getResponseHeader("Content-Length");fncCallback(this)}else{if(fncError)fncError()}oHTTP=null}}}}oHTTP.open("GET",strURL,true);if(oHTTP.overrideMimeType)oHTTP.overrideMimeType('text/plain; charset=x-user-defined');if(aRange&&bAcceptRanges){oHTTP.setRequestHeader("Range","bytes="+aRange[0]+"-"+aRange[1])}oHTTP.setRequestHeader("If-Modified-Since","Sat, 1 Jan 1970 00:00:00 GMT");oHTTP.send(null)}else{if(fncError)fncError()}}return function(strURL,fncCallback,fncError,aRange){if(aRange){getHead(strURL,function(oHTTP){var iLength=parseInt(oHTTP.getResponseHeader("Content-Length"),10);var strAcceptRanges=oHTTP.getResponseHeader("Accept-Ranges");var iStart,iEnd;iStart=aRange[0];if(aRange[0]<0)iStart+=iLength;iEnd=iStart+aRange[1]-1;sendRequest(strURL,fncCallback,fncError,[iStart,iEnd],(strAcceptRanges=="bytes"),iLength)})}else{sendRequest(strURL,fncCallback,fncError)}}}());document.write("<script type='text/vbscript'>\r\n"+"Function IEBinary_getByteAt(strBinary, iOffset)\r\n"+"	IEBinary_getByteAt = AscB(MidB(strBinary,iOffset+1,1))\r\n"+"End Function\r\n"+"Function IEBinary_getLength(strBinary)\r\n"+"	IEBinary_getLength = LenB(strBinary)\r\n"+"End Function\r\n"+"</script>\r\n");var EXIF={};(function(){var bDebug=false;EXIF.Tags={0x9000:"ExifVersion",0xA000:"FlashpixVersion",0xA001:"ColorSpace",0xA002:"PixelXDimension",0xA003:"PixelYDimension",0x9101:"ComponentsConfiguration",0x9102:"CompressedBitsPerPixel",0x927C:"MakerNote",0x9286:"UserComment",0xA004:"RelatedSoundFile",0x9003:"DateTimeOriginal",0x9004:"DateTimeDigitized",0x9290:"SubsecTime",0x9291:"SubsecTimeOriginal",0x9292:"SubsecTimeDigitized",0x829A:"ExposureTime",0x829D:"FNumber",0x8822:"ExposureProgram",0x8824:"SpectralSensitivity",0x8827:"ISOSpeedRatings",0x8828:"OECF",0x9201:"ShutterSpeedValue",0x9202:"ApertureValue",0x9203:"BrightnessValue",0x9204:"ExposureBias",0x9205:"MaxApertureValue",0x9206:"SubjectDistance",0x9207:"MeteringMode",0x9208:"LightSource",0x9209:"Flash",0x9214:"SubjectArea",0x920A:"FocalLength",0xA20B:"FlashEnergy",0xA20C:"SpatialFrequencyResponse",0xA20E:"FocalPlaneXResolution",0xA20F:"FocalPlaneYResolution",0xA210:"FocalPlaneResolutionUnit",0xA214:"SubjectLocation",0xA215:"ExposureIndex",0xA217:"SensingMethod",0xA300:"FileSource",0xA301:"SceneType",0xA302:"CFAPattern",0xA401:"CustomRendered",0xA402:"ExposureMode",0xA403:"WhiteBalance",0xA404:"DigitalZoomRation",0xA405:"FocalLengthIn35mmFilm",0xA406:"SceneCaptureType",0xA407:"GainControl",0xA408:"Contrast",0xA409:"Saturation",0xA40A:"Sharpness",0xA40B:"DeviceSettingDescription",0xA40C:"SubjectDistanceRange",0xA005:"InteroperabilityIFDPointer",0xA420:"ImageUniqueID"};EXIF.TiffTags={0x0100:"ImageWidth",0x0101:"ImageHeight",0x8769:"ExifIFDPointer",0x8825:"GPSInfoIFDPointer",0xA005:"InteroperabilityIFDPointer",0x0102:"BitsPerSample",0x0103:"Compression",0x0106:"PhotometricInterpretation",0x0112:"Orientation",0x0115:"SamplesPerPixel",0x011C:"PlanarConfiguration",0x0212:"YCbCrSubSampling",0x0213:"YCbCrPositioning",0x011A:"XResolution",0x011B:"YResolution",0x0128:"ResolutionUnit",0x0111:"StripOffsets",0x0116:"RowsPerStrip",0x0117:"StripByteCounts",0x0201:"JPEGInterchangeFormat",0x0202:"JPEGInterchangeFormatLength",0x012D:"TransferFunction",0x013E:"WhitePoint",0x013F:"PrimaryChromaticities",0x0211:"YCbCrCoefficients",0x0214:"ReferenceBlackWhite",0x0132:"DateTime",0x010E:"ImageDescription",0x010F:"Make",0x0110:"Model",0x0131:"Software",0x013B:"Artist",0x8298:"Copyright"};EXIF.GPSTags={0x0000:"GPSVersionID",0x0001:"GPSLatitudeRef",0x0002:"GPSLatitude",0x0003:"GPSLongitudeRef",0x0004:"GPSLongitude",0x0005:"GPSAltitudeRef",0x0006:"GPSAltitude",0x0007:"GPSTimeStamp",0x0008:"GPSSatellites",0x0009:"GPSStatus",0x000A:"GPSMeasureMode",0x000B:"GPSDOP",0x000C:"GPSSpeedRef",0x000D:"GPSSpeed",0x000E:"GPSTrackRef",0x000F:"GPSTrack",0x0010:"GPSImgDirectionRef",0x0011:"GPSImgDirection",0x0012:"GPSMapDatum",0x0013:"GPSDestLatitudeRef",0x0014:"GPSDestLatitude",0x0015:"GPSDestLongitudeRef",0x0016:"GPSDestLongitude",0x0017:"GPSDestBearingRef",0x0018:"GPSDestBearing",0x0019:"GPSDestDistanceRef",0x001A:"GPSDestDistance",0x001B:"GPSProcessingMethod",0x001C:"GPSAreaInformation",0x001D:"GPSDateStamp",0x001E:"GPSDifferential"};EXIF.StringValues={ExposureProgram:{0:"Not defined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"},MeteringMode:{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"},LightSource:{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"},Flash:{0x0000:"Flash did not fire",0x0001:"Flash fired",0x0005:"Strobe return light not detected",0x0007:"Strobe return light detected",0x0009:"Flash fired, compulsory flash mode",0x000D:"Flash fired, compulsory flash mode, return light not detected",0x000F:"Flash fired, compulsory flash mode, return light detected",0x0010:"Flash did not fire, compulsory flash mode",0x0018:"Flash did not fire, auto mode",0x0019:"Flash fired, auto mode",0x001D:"Flash fired, auto mode, return light not detected",0x001F:"Flash fired, auto mode, return light detected",0x0020:"No flash function",0x0041:"Flash fired, red-eye reduction mode",0x0045:"Flash fired, red-eye reduction mode, return light not detected",0x0047:"Flash fired, red-eye reduction mode, return light detected",0x0049:"Flash fired, compulsory flash mode, red-eye reduction mode",0x004D:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",0x004F:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",0x0059:"Flash fired, auto mode, red-eye reduction mode",0x005D:"Flash fired, auto mode, return light not detected, red-eye reduction mode",0x005F:"Flash fired, auto mode, return light detected, red-eye reduction mode"},SensingMethod:{1:"Not defined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"},SceneCaptureType:{0:"Standard",1:"Landscape",2:"Portrait",3:"Night scene"},SceneType:{1:"Directly photographed"},CustomRendered:{0:"Normal process",1:"Custom process"},WhiteBalance:{0:"Auto white balance",1:"Manual white balance"},GainControl:{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"},Contrast:{0:"Normal",1:"Soft",2:"Hard"},Saturation:{0:"Normal",1:"Low saturation",2:"High saturation"},Sharpness:{0:"Normal",1:"Soft",2:"Hard"},SubjectDistanceRange:{0:"Unknown",1:"Macro",2:"Close view",3:"Distant view"},FileSource:{3:"DSC"},Components:{0:"",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"}};function addEvent(oElement,strEvent,fncHandler){if(oElement.addEventListener){oElement.addEventListener(strEvent,fncHandler,false)}else if(oElement.attachEvent){oElement.attachEvent("on"+strEvent,fncHandler)}}function imageHasData(oImg){return!!(oImg.exifdata)}function getImageData(oImg,fncCallback){BinaryAjax(oImg.src,function(oHTTP){var oEXIF=findEXIFinJPEG(oHTTP.binaryResponse);oImg.exifdata=oEXIF||{};if(fncCallback)fncCallback()})}function findEXIFinJPEG(oFile){var aMarkers=[];if(oFile.getByteAt(0)!=0xFF||oFile.getByteAt(1)!=0xD8){return false}var iOffset=2;var iLength=oFile.getLength();while(iOffset<iLength){if(oFile.getByteAt(iOffset)!=0xFF){if(bDebug)console.log("Not a valid marker at offset "+iOffset+", found: "+oFile.getByteAt(iOffset));return false}var iMarker=oFile.getByteAt(iOffset+1);if(iMarker==22400){if(bDebug)console.log("Found 0xFFE1 marker");return readEXIFData(oFile,iOffset+4,oFile.getShortAt(iOffset+2,true)-2);iOffset+=2+oFile.getShortAt(iOffset+2,true)}else if(iMarker==225){if(bDebug)console.log("Found 0xFFE1 marker");return readEXIFData(oFile,iOffset+4,oFile.getShortAt(iOffset+2,true)-2)}else{iOffset+=2+oFile.getShortAt(iOffset+2,true)}}}function readTags(oFile,iTIFFStart,iDirStart,oStrings,bBigEnd){var iEntries=oFile.getShortAt(iDirStart,bBigEnd);var oTags={};for(var i=0;i<iEntries;i++){var iEntryOffset=iDirStart+i*12+2;var strTag=oStrings[oFile.getShortAt(iEntryOffset,bBigEnd)];if(!strTag&&bDebug)console.log("Unknown tag: "+oFile.getShortAt(iEntryOffset,bBigEnd));oTags[strTag]=readTagValue(oFile,iEntryOffset,iTIFFStart,iDirStart,bBigEnd)}return oTags}function readTagValue(oFile,iEntryOffset,iTIFFStart,iDirStart,bBigEnd){var iType=oFile.getShortAt(iEntryOffset+2,bBigEnd);var iNumValues=oFile.getLongAt(iEntryOffset+4,bBigEnd);var iValueOffset=oFile.getLongAt(iEntryOffset+8,bBigEnd)+iTIFFStart;switch(iType){case 1:case 7:if(iNumValues==1){return oFile.getByteAt(iEntryOffset+8,bBigEnd)}else{var iValOffset=iNumValues>4?iValueOffset:(iEntryOffset+8);var aVals=[];for(var n=0;n<iNumValues;n++){aVals[n]=oFile.getByteAt(iValOffset+n)}return aVals}break;case 2:var iStringOffset=iNumValues>4?iValueOffset:(iEntryOffset+8);return oFile.getStringAt(iStringOffset,iNumValues-1);break;case 3:if(iNumValues==1){return oFile.getShortAt(iEntryOffset+8,bBigEnd)}else{var iValOffset=iNumValues>2?iValueOffset:(iEntryOffset+8);var aVals=[];for(var n=0;n<iNumValues;n++){aVals[n]=oFile.getShortAt(iValOffset+2*n,bBigEnd)}return aVals}break;case 4:if(iNumValues==1){return oFile.getLongAt(iEntryOffset+8,bBigEnd)}else{var aVals=[];for(var n=0;n<iNumValues;n++){aVals[n]=oFile.getLongAt(iValueOffset+4*n,bBigEnd)}return aVals}break;case 5:if(iNumValues==1){return oFile.getLongAt(iValueOffset,bBigEnd)/oFile.getLongAt(iValueOffset+4,bBigEnd)}else{var aVals=[];for(var n=0;n<iNumValues;n++){aVals[n]=oFile.getLongAt(iValueOffset+8*n,bBigEnd)/oFile.getLongAt(iValueOffset+4+8*n,bBigEnd)}return aVals}break;case 9:if(iNumValues==1){return oFile.getSLongAt(iEntryOffset+8,bBigEnd)}else{var aVals=[];for(var n=0;n<iNumValues;n++){aVals[n]=oFile.getSLongAt(iValueOffset+4*n,bBigEnd)}return aVals}break;case 10:if(iNumValues==1){return oFile.getSLongAt(iValueOffset,bBigEnd)/oFile.getSLongAt(iValueOffset+4,bBigEnd)}else{var aVals=[];for(var n=0;n<iNumValues;n++){aVals[n]=oFile.getSLongAt(iValueOffset+8*n,bBigEnd)/oFile.getSLongAt(iValueOffset+4+8*n,bBigEnd)}return aVals}break}}function readEXIFData(oFile,iStart,iLength){if(oFile.getStringAt(iStart,4)!="Exif"){if(bDebug)console.log("Not valid EXIF data! "+oFile.getStringAt(iStart,4));return false}var bBigEnd;var iTIFFOffset=iStart+6;if(oFile.getShortAt(iTIFFOffset)==0x4949){bBigEnd=false}else if(oFile.getShortAt(iTIFFOffset)==0x4D4D){bBigEnd=true}else{if(bDebug)console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)");return false}if(oFile.getShortAt(iTIFFOffset+2,bBigEnd)!=0x002A){if(bDebug)console.log("Not valid TIFF data! (no 0x002A)");return false}if(oFile.getLongAt(iTIFFOffset+4,bBigEnd)!=0x00000008){if(bDebug)console.log("Not valid TIFF data! (First offset not 8)",oFile.getShortAt(iTIFFOffset+4,bBigEnd));return false}var oTags=readTags(oFile,iTIFFOffset,iTIFFOffset+8,EXIF.TiffTags,bBigEnd);if(oTags.ExifIFDPointer){var oEXIFTags=readTags(oFile,iTIFFOffset,iTIFFOffset+oTags.ExifIFDPointer,EXIF.Tags,bBigEnd);for(var strTag in oEXIFTags){switch(strTag){case"LightSource":case"Flash":case"MeteringMode":case"ExposureProgram":case"SensingMethod":case"SceneCaptureType":case"SceneType":case"CustomRendered":case"WhiteBalance":case"GainControl":case"Contrast":case"Saturation":case"Sharpness":case"SubjectDistanceRange":case"FileSource":oEXIFTags[strTag]=EXIF.StringValues[strTag][oEXIFTags[strTag]];break;case"ExifVersion":case"FlashpixVersion":oEXIFTags[strTag]=String.fromCharCode(oEXIFTags[strTag][0],oEXIFTags[strTag][1],oEXIFTags[strTag][2],oEXIFTags[strTag][3]);break;case"ComponentsConfiguration":oEXIFTags[strTag]=EXIF.StringValues.Components[oEXIFTags[strTag][0]]+EXIF.StringValues.Components[oEXIFTags[strTag][1]]+EXIF.StringValues.Components[oEXIFTags[strTag][2]]+EXIF.StringValues.Components[oEXIFTags[strTag][3]];break}oTags[strTag]=oEXIFTags[strTag]}}if(oTags.GPSInfoIFDPointer){var oGPSTags=readTags(oFile,iTIFFOffset,iTIFFOffset+oTags.GPSInfoIFDPointer,EXIF.GPSTags,bBigEnd);for(var strTag in oGPSTags){switch(strTag){case"GPSVersionID":oGPSTags[strTag]=oGPSTags[strTag][0]+"."+oGPSTags[strTag][1]+"."+oGPSTags[strTag][2]+"."+oGPSTags[strTag][3];break}oTags[strTag]=oGPSTags[strTag]}}return oTags}EXIF.getData=function(oImg,fncCallback){if(!oImg.complete)return false;if(!imageHasData(oImg)){getImageData(oImg,fncCallback)}else{if(fncCallback)fncCallback()}return true};EXIF.getTag=function(oImg,strTag){if(!imageHasData(oImg))return;return oImg.exifdata[strTag]};EXIF.getAllTags=function(oImg){if(!imageHasData(oImg))return{};var oData=oImg.exifdata;var oAllTags={};for(var a in oData){if(oData.hasOwnProperty(a)){oAllTags[a]=oData[a]}}return oAllTags};EXIF.pretty=function(oImg){if(!imageHasData(oImg))return"";var oData=oImg.exifdata;var strPretty="";for(var a in oData){if(oData.hasOwnProperty(a)){if(typeof oData[a]=="object"){strPretty+=a+" : ["+oData[a].length+" values]\r\n"}else{strPretty+=a+" : "+oData[a]+"\r\n"}}}return strPretty};EXIF.readFromBinaryFile=function(oFile){return findEXIFinJPEG(oFile)};jQuery.fn.exifLoad=function(fncCallback){return this.each(function(){EXIF.getData(this,fncCallback)})};jQuery.fn.exif=function(strTag){var aStrings=[];this.each(function(){aStrings.push(EXIF.getTag(this,strTag))});return aStrings};jQuery.fn.exifAll=function(){var aStrings=[];this.each(function(){aStrings.push(EXIF.getAllTags(this))});return aStrings};jQuery.fn.exifPretty=function(){var aStrings=[];this.each(function(){aStrings.push(EXIF.pretty(this))});return aStrings}})()})();

	var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
	Math.uuid = function() {
		var chars = CHARS, uuid = new Array(36), rnd=0, r;
		for (var i = 0; i < 36; i++) {
			if (i==8 || i==13 ||  i==18 || i==23) {
				uuid[i] = '-';
			} else if (i==14) {
				uuid[i] = '4';
			} else {
				if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
				r = rnd & 0xf;
				rnd = rnd >> 4;
				uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
			}
		}
		return uuid.join('');
	};

	/**
	 * 图片角度矫正
	 * @author rubekid
	 * 2015-01-25
	 */
	function correctOrientation(canvas, image, context, orientation){
		var _canvas = document.createElement('canvas');
		var width = canvas.width;
		var height = canvas.height;
		var ow = width, oh = height;
		switch (orientation) {
			case 5:
			case 6:
			case 7:
			case 8:
				width = canvas.height;
				height = canvas.width;
				break;
			default:
				break;
		}
		_canvas.width = width;
		_canvas.height = height;
		var ctx = _canvas.getContext('2d');
		ctx.save();
		switch (orientation) {
			case 2:
				//水平翻转
				ctx.translate(width, 0);
				ctx.scale(-1, 1);
				break;
			case 3:
				//180向左旋转
				ctx.translate(width, height);
				ctx.rotate(Math.PI);
				break;
			case 4:
				//垂直翻转
				ctx.translate(0, height);
				ctx.scale(1, -1);
				break;
			case 5:
				//垂直翻转+90右移
				ctx.rotate(0.5 * Math.PI);
				ctx.scale(1, -1);
				break;
			case 6:
				//90右旋
				ctx.rotate(0.5 * Math.PI);
				ctx.translate(0, -oh);
				break;
			case 7:
				//水平翻转+90右移
				ctx.rotate(0.5 * Math.PI);
				ctx.translate(ow, -oh);
				ctx.scale(-1, 1);
				break;
			case 8:
				//90向左旋转
				ctx.rotate(-0.5 * Math.PI);
				ctx.translate(-ow, 0);
				break;
			default:
				break;
		}
		ctx.drawImage(image, 0, 0, ow, oh);
		ctx.restore();
		context.clearRect(0, 0, canvas.width, canvas.height);
		canvas.width = width;
		canvas.height = height;
		context.drawImage(_canvas, 0, 0, canvas.width, canvas.height);
	}


	/**
	 * version 1.1
	 * author rubekid
	 */

	var H5Uploader = window.H5Uploader || {};
	var _BlobBuilder = window.BlobBuilder || window.MSBlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
	var _URL = window.URL || window.webkitURL;
	window.H5Uploader = H5Uploader;

	H5Uploader.ErrorCode ={
		SIZE_LIMIT_ERROR : 100,
		QUEUE_LIMIT_ERROR : 101,
		UPLOAD_LIMIT_ERROR : 102,
		TYPE_ERROR :103,
		SIZE_ERROR : 104

	};

	H5Uploader.Mimes = {
		"jpg":["image/jpg", "image/pjpeg"],
		"jpeg":["image/jpg", "image/pjpeg"],
		"png":["image/png", "image/x-png"],
		"gif":"image/gif"
	}


	H5Uploader.Utils = {
		formatFileSize : function(size){
			if (size> 1024 * 1024){
				size = (Math.round(size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
			}
			else{
				size = (Math.round(size * 100 / 1024) / 100).toString() + 'KB';
			}
			return size;
		}
	};

	/**
	 * 图片管理
	 */
	H5Uploader.ImageUtils = {
		redraw:function(image, options){
			//生成比例
			var ow =  image.width,
				oh = image.height,
				scale = ow / oh,
				maxW = options.mWidth||ow,
				maxH = options.mHeight||oh,
				w=ow,h=oh;
			if(ow > maxW || oh > maxH){
				if(scale >= maxW / maxH){
					w = maxW;
					h =  w / scale;
				}
				else{
					h = maxH;
					w = h * scale;
				}
			}

			//生成canvas
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			canvas.width = w;
			canvas.height = h;
			ctx.drawImage(image, 0, 0, w, h);

			var mimeType = options.mimeType||'image/jpeg';
			var base64;
			var ua = window.navigator.userAgent.toLowerCase();
			// 修复IOS
			if( ua.match(/iphone|ipad/i)) {
				var mpImg = new MegaPixImage(image);
				var opt = { maxWidth: w, maxHeight: h, quality: options.quality || 0.8};
				if(options.orientation){
					opt.orientation = options.orientation;
				}
				mpImg.render(canvas, opt);
				base64 = canvas.toDataURL(mimeType, options.quality || 0.8 );
			}else if( ua.match(/android/i) ) {// 修复android
				if(options.orientation){//图片角度矫正
					correctOrientation(canvas, image, ctx, options.orientation);
				}
				var encoder = new JPEGEncoder();
				base64 = encoder.encode(ctx.getImageData( 0, 0, canvas.width, canvas.height), options.quality * 100 || 80 );
			}
			else{
				base64 = canvas.toDataURL(mimeType, options.quality || 0.8 );
			}

			// 生成结果
			return {
				base64 : base64,
				clearBase64: base64.substr( base64.indexOf(',') + 1 )
			};
		}
	};

	/**
	 * 文件管理
	 */
	H5Uploader.FileManager = function(options){
		this.init(options);
	};
	H5Uploader.FileManager.prototype = {
		_id:null,
		_file:null,
		_mimeType:"",
		_src:"",
		_base64:"",
		init:function(options){
			this._id = options.id || Math.uuid();
			this._file = options.file;
			this._mimeType = options.mimeType;
			this._src = _URL.createObjectURL(this._file);
		},
		getItemData:function(){
			var file = this._file;
			var fileSize = Math.round(file.size / 1024);
			var suffix   = 'KB';
			if (fileSize > 1000) {
				fileSize = Math.round(fileSize / 1000);
				suffix   = 'MB';
			}
			var fileSizeParts = fileSize.toString().split('.');
			fileSize = fileSizeParts[0];
			if (fileSizeParts.length > 1) {
				fileSize += '.' + fileSizeParts[1].substr(0,2);
			}
			fileSize += suffix;
			// Truncate the filename if it's too long
			var fileName = file.name;
			if (fileName.length > 25) {
				fileName = fileName.substr(0,25) + '...';
			}
			return {
				'fileID'     : this._id,
				'fileName'   : fileName,
				'fileSize'   : fileSize
			}
		},
		setId:function(id){
			this._id = id;
		},
		getId:function(){
			return this._id;
		},
		setFile:function(file){
			this._file = file;
		},
		getFile:function(){
			return this._file;
		},
		setMimeType:function(mimeType){
			this._mimeType = mimeType;
		},
		getMimeType:function(){
			return this._mimeType;
		},
		setSrc:function(src){
			this._src = src;
		},
		getSrc:function(src){
			return this._src;
		},
		setBase64:function(base64){
			this._base64 = base64;
		},
		getBase64:function(){
			return this._base64;
		}
	};

	/**
	 * 上传控件
	 */
	H5Uploader.Uploader = function(options){
		this.init(options);
	};
	H5Uploader.Uploader.prototype={
		/**
		 * 每次重新生成  防止 value 不能重置造成change失效
		 */
		_fileInputTpl:'<input type="file" class="needsclick" id="html5FileInput" name="userfile" />',
		init:function(options){
			this.uuid = Math.uuid();
			this._options = options;
			this._maxPhotoWidth = options.maxPhotoWidth || 960;
			this._maxPhotoHeight = options.maxPhotoHeight || 960;
			this._redraw = options.redraw;
			this._fileObjName = options.fileObjName || "userfile";
			this._button = options.button;
			this._uploaderUrl = options.uploader || options.uploaderUrl;
			this._tmpImages = {};
			this._initAllowExts();
			this.initElement();
			this.uploadedCount = 0;
			this.queueLength = 0;
			this.bindEvent();
		},
		initElement:function(){
			this._uploadForm = $('<form name="uploadForm" target="uploadIframe" style="position:absolute;left:-9999px;top:0px;" enctype="multipart/form-data" method="post"></form>');
			this._fileInput = $(this._fileInputTpl);
			this._iframeAreaWrap = $('<div style="display:none;"></div>');
			this._uploadForm.appendTo(document.body);
			this._fileInput.appendTo(this._uploadForm);
			this._fileInput.css({"width":"100%", "opacity":"0"});
			this._iframeAreaWrap.appendTo(document.body);
			this._fileInput.attr("name", this._fileObjName);
			if(this._options.multi){
				this._fileInput.attr("multiple", "multiple");	//开启不支持iphone的弹出菜单栏
			}
			this._fileInput.attr("accept", "image/jpg,image/jpeg,image/png,image/gif");
			this._queue = $('<div id="upload-queue-'+ this.uuid +'" class="uploadify-queue"></div>');
			if(this._options.showProgress){
				this._button.after(this._queue);
			}
		},
		appendItem:function(item, index){
			var itemEle = $('<div id="queue-item-'+item.fileID+'" class="uploadify-queue-item"> '+
				'    <span class="fileName" title="'+ item.fileName +'">'+item.fileName+'</span>'+
				'    <span class="filesize">('+item.fileSize+')</span>'+
				'    <div class="uploadify-progress"> '+
				'     <div class="uploadify-progress-bar" style="width: 0%;">'+
				'     </div> '+
				'    </div> '+
				'   </div>');
			this._queue.append(itemEle);

		},
		destory:function(){
			this._uploadForm.remove();
			this._iframeAreaWrap.remove();
			console.log("destory complete");
		},
		createTmpImage:function(src){//创建一个隐藏的img标签用来获取图片显示的宽高
			this.removeTmpImage(src);
			this._tmpImages[src] = $("<img />");
			this._tmpImages[src].appendTo(document.body);
			this._tmpImages[src].attr("src", src);
			this._tmpImages[src].hide();
		},
		removeTmpImage:function(src){
			if(this._tmpImages[src]){
				this._tmpImages[src].remove();
			}
		},
		bindEvent:function(){
			var _this = this;
			this._button.bind("click", function(){
				if(typeof _this._options.beforeClick == "function"){
					_this._options.beforeClick();
				}
				_this._fileInput.trigger("click");
				if(typeof _this._options.afterClick == "function"){
					_this._options.afterClick();
				}
			});

			this._fileInput.bind({
				change:function(e){
					if($.trim($(this).val())==""){
						return ;
					}
					var files = e.target.files || e.dataTransfer.files;

					if(!_this._checkSize(files)){
						_this.showError(H5Uploader.ErrorCode.SIZE_ERROR, "获取文件大小异常。");
						_this.clearFileInput();
						return false;
					}

					if(!_this._checkType(files)){
						_this.showError(H5Uploader.ErrorCode.TYPE_ERROR, "只能上传格式为" + _this._options.fileTypeExts+"。");
						_this.clearFileInput();
						return false;
					}

					if(!_this._checkQueueLimit(files)){
						_this.showError(H5Uploader.ErrorCode.QUEUE_LIMIT_ERROR, "一次最多只能上传" + _this._options.queueSizeLimit + "个文件。");
						_this.clearFileInput();
						return  false;
					}
					if(!_this._checkUploadLimit(files)){
						_this.clearFileInput();
						return  false;
					}

					var fileUpload = function(){

						if(!_this._checkSizeLimit(files)){
							_this.showError(H5Uploader.ErrorCode.SIZE_LIMIT_ERROR, "文件大小不能超过" + H5Uploader.Utils.formatFileSize(_this._options.fileSizeLimit) +"。");
							_this.clearFileInput();
							return false;
						}


						var upload = function(){
							_this.uploadedCount = 0;
							_this.queueLength = files.length;
							if(_this._options.beforeUpload() === false){
								return false;
							}
							$.each(files, function(){
								var fileManager = new H5Uploader.FileManager({file:this, mimeType:this.type||_this._getMimeType(this.name||this.fileName)});
								_this.appendItem(fileManager.getItemData(),
									$(this).index());
								_this.ajaxUpload(fileManager);
							});

							_this.clearFileInput();
						}

						if(typeof _this._options.confirmUpload == "function"){
							_this._options.confirmUpload(files, upload);

						}
						else{
							upload();
						}
					};


					if(_this._redraw){
						//图片压缩转换
						var blobs = [];
						var finishCount = 0;

						var appendFiles = function(file){
							blobs.push(file);
							finishCount ++;
							if(finishCount == files.length){//等待所有完成在进行上传
								files  = blobs;
								fileUpload();
							}
						};

						var redrawPhoto = function(image, mimeType, file, orientation){
							try{
								var data = H5Uploader.ImageUtils.redraw(image,
									{
										mimeType:mimeType,
										orientation : orientation,
										mWidth:_this._maxPhotoWidth,
										mHeight:_this._maxPhotoHeight
									});
								var bin = atob(data.clearBase64);
								var buffer = new Uint8Array(bin.length);
								for (var i = 0; i < bin.length; i++) {
									buffer[i] = bin.charCodeAt(i);
								}
								var blob = null;
								try{
									blob = new Blob([buffer.buffer], {type: mimeType});
								}
								catch(e){
									if(_BlobBuilder){
										var blobBuilder = new _BlobBuilder();
										blobBuilder.append(buffer.buffer);
										blob = blobBuilder.getBlob(mimeType);
									}
								}
								if(blob == null){
									return file;
								}
								//若重绘后变大 抛弃掉
								if(file.size > blob.size || (orientation && orientation != 1)){
									blob.name = file.name;
									return new File([blob], file.name, {type: mimeType});
								}
							}
							catch(e){}
							return file;
						}


						$.each(files, function(){
							var fileName = this.name||this.fileName;
							var mimeType = this.type||_this._getMimeType(fileName);
							var blob = _URL.createObjectURL(this);
							var _file = this;
							_this.createTmpImage(blob);
							var image = new Image();
							image.onload = function(){

								try{
									if(mimeType != "image/gif"){
										var _src = this.src;
										var _orientation = null;
										try{
											var tmpImage = _this._tmpImages[_src];
											tmpImage.exifLoad(function(){
												_orientation = tmpImage.exif("Orientation");
												if(_orientation){
													_orientation = _orientation[0];
												}
												_this.removeTmpImage(_src);
												var mewFile = redrawPhoto(image, mimeType, _file, _orientation);
												appendFiles(mewFile);

											});
										}
										catch(e){
											var mewFile = redrawPhoto(image, mimeType, _file, _orientation);
											appendFiles(mewFile);
										}
									}
									else{
										appendFiles(_file);
									}
									_URL.revokeObjectURL(_src);
								}
								catch(e){
									appendFiles(_file);
								}
							};
							image.src = blob;
						});
					}
					else{
						fileUpload();
					}

				}
			});
		},
		clearFileInput:function(){
			this._fileInput.val("");
		},
		upload:function(fileManager){
			this.ajaxUpload(fileManager);
		},
		ajaxUpload:function(fileManager){
			var file = fileManager.getFile();
			var _this = this;
			var xhr = new XMLHttpRequest();
			if (xhr.upload) {
				xhr.upload.addEventListener("progress", function(e) {
					_this._onProgress(fileManager, e.loaded, e.total);
				}, false);
				xhr.onreadystatechange = function(e) {
					if (xhr.readyState == 4) {
						_this.uploadedCount ++;
						if (xhr.status == 200 ||xhr.status == 0) {
							$("#queue-item-" + fileManager.getId()).remove();
							_this._onUploadSuccess(fileManager, xhr.responseText);

						} else {
							_this._onUploadError(fileManager, xhr.responseText);
						}
						if(_this.uploadedCount == _this.queueLength){
							_this._onUploadComplete();
						}
					}
				};
				this._onUploadStart(fileManager, function(){
					var formData  = new FormData();

					var file = fileManager.getFile();
					xhr.open('POST', _this._getUploader(), true);
					xhr.setRequestHeader("content-length", file.size);
					formData.append(_this._fileObjName, file);
					for(var i in _this._options.formData){
						formData.append(i, _this._options.formData[i]);
					}
					xhr.send(formData);

				});

			}
		},
		_getUploader:function(){
			var url = this._uploaderUrl;
			if(typeof this._options.createUrl == "function"){
				url = this._options.createUrl(url);
			}
			return url;
		},
		_initAllowExts:function(){
			var allowTypes = [];
			if(this._options.fileTypes){
				var exts = this._options.fileTypes.split(",");
				for(var i in exts){
					if(exts[i] !="*.*"){
						allowTypes.push(exts[i]);
					}
				}
			}
			this._allowTypes = allowTypes;
		},
		_onProgress:function(fileManager, loaded, total){
			this._options.onProgress(fileManager, loaded, total);
		},
		_onUploadStart:function(fileManager, startUpload){
			$("#upload-queue-" + this.uuid).show();
			var _this = this;
			var file = fileManager.getFile();
			var appendImage = function(base64){
				fileManager.setBase64(base64);
				if(_this._options.onUploadStart(fileManager) === false){
					return false;
				}
				startUpload();
			};

			//对路径进行压缩
			var reader = new FileReader();
			reader.onload = function(e) {
				var src = e.target.result;
				if(src.indexOf('data:base64')==0){ //兼容有些浏览器获取base64时丢失类型信息 
					var mimeType = fileManager.getMimeType();
					src  = src.replace(/^data:base64/, 'data:'+mimeType+';base64');
				}
				appendImage(src);
			}
			reader.readAsDataURL(file);
		},
		_onUploadSuccess:function(fileManager, response){
			this._options.onUploadSuccess(fileManager, response);
			$("#queue-item-" + fileManager.getId()).remove();
		},
		_onUploadError:function(fileManager, response){
			this._options.onUploadError(fileManager, response);
		},
		_onUploadComplete:function(){
			$("#upload-queue-" + this.uuid).hide();
			this._options.onUploadComplete();
		},
		_checkSize:function(files){
			var bool = true;
			var _this = this;
			$.each(files, function(){
				if(!this.size){
					bool = false;
					return false;
				}
			});
			return bool;
		},
		_checkSizeLimit:function(files){
			var bool = true;
			var _this = this;
			if(this._options.fileSizeLimit){
				$.each(files, function(){
					if(!this.size || this.size > _this._options.fileSizeLimit){
						bool = false;
						return false;
					}
				});
			}
			return bool;
		},
		_checkType:function(files){
			var bool = true;
			var _this = this;
			if(this._allowTypes){
				$.each(files, function(){
					var type = this.type;
					if(!type){
						type = _this._getMimeType(this.name||this.fileName||"");
					}
					if($.inArray(type, _this._allowTypes)==-1){
						bool = false;
						return false;
					}
				});
			}
			return bool;
		},
		_checkQueueLimit:function(files){
			if(this._options.queueSizeLimit && files.length > this._options.queueSizeLimit){
				return false;
			}
			
			return true;
		},
		_checkUploadLimit:function(files){
			if(this._options.checkUploadLimit(files.length) === false){
				return false;
			}
			return true;
		},
		_getExtension:function(fileName){
			return fileName.substring(fileName.lastIndexOf('.')+1);
		},
		_getMimeType:function(fileName){
			var type = H5Uploader.Mimes[this._getExtension(fileName)];
			if(type && (typeof type=="Array" || typeof type=="object")){
				return type[0];
			}
			return type;
		},
		showError:function(code, message){
			if(typeof this._options.showError == "function"){
				this._options.showError(code, message);
			}
			else{
				alert(message);
			}
		}
	};


	(function($){
		var methods = {
			init:function(options){
				return this.each(function(){
					var $this = $(this);
					var $clone = $this.clone();
					var settings = $.extend({
						id : $this.attr('id'),
						button:$this,
						uploader : '',
						formData:{},
						auto : true,
						fileTypes : '*.*',
						multi : false,
						fileSizeLimit: 0,
						queueSizeLimit:1,
						checkUploadLimit:function(size){return true;},//检测总上传数量
						onUploadStart:function(fileManager){return true;},//上传开始时的动作
						onUploadSuccess:function(fileManager, response){},//上传成功的动作
						onUploadComplete:function(fileManager){},//上传完成的动作
						onUploadError:function(fileManager, response){},//上传失败的动作
						onProgress:function(fileManager, loaded, total){
							$("#queue-item-" + fileManager.getId() + " .uploadify-progress-bar").width(((loaded * 100) / total) + "%");
						},//上传进度
						onInit:function(){},//初始化时的动作
						beforeUpload:function(){}, //开始上传前执行
					},options);

					this._uploader = new H5Uploader.Uploader(settings);
				});
			},
			destory:function(){
				return this.each(function(){
					if(this._uploader){
						this._uploader.destory();
					}
				});

			}
		};
		$.fn.html5uploader = function(method){

			if (methods[method]) {
				return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
			} else if (typeof method === 'object' || !method) {
				return methods.init.apply(this, arguments);
			} else {
				$.error('The method ' + method + ' does not exist in $.html5uploader');
			}
		};

		$.fn.H5ImageUploader = function(options){
			var _setting = {
				fileObjName:"image",
				fileTypes:"image/jpg,image/jpeg,image/png,image/gif,image/bmp,image/x-ms-bmp",
				fileSizeLimit:2*1024*1024,
				fileTypeExts:"*.jpg,*.png,*.gif,*.bmp"

			};
			return this.html5uploader($.extend(true, {}, _setting, options));
		};
	})(window.jQuery|| window.Zepto);
})();

